﻿#include "logincontroller.h"
#include <QCryptographicHash>

LoginController::LoginController()
{
    //m_pHelper = DbMgr::instance()->getHelper();

    m_mapFunc.insert("/login",   &LoginController::login);      //登录
    m_mapFunc.insert("/logout",  &LoginController::logout);     //登出
}

void LoginController::service(HttpRequest& request, HttpResponse& response)
{
    QByteArray path = request.getPath().toLower();
    if(m_mapFunc.contains(path))
    {
        pServFunc func = m_mapFunc.value(path);
        (this->*func)(request, response);
    }
}


void LoginController::login(HttpRequest& request, HttpResponse& response)
{
    ResultJson ret(0, true, QStringLiteral("登入成功"));

    QString body = request.getBody();
    QString username = request.getParameter("username");
    QString password = request.getParameter("password");
    QString vercode = request.getParameter("vercode");
    QString access_token = request.getParameter("access_token");

    QString codeid = request.getParameter("codeid");

    HttpSession session = sessionStore->getSession(request, response, true);

    if(username.isEmpty())
    {
        ret.failedMsg(QStringLiteral("用户名为空"));
        response.write(ret.toString().toLocal8Bit());
        return;
    }
    if(password.isEmpty())
    {
        ret.failedMsg(QStringLiteral("密码为空"));
        response.write(ret.toString().toLocal8Bit());
        return;
    }
    if(vercode.isEmpty())
    {
        ret.failedMsg(QStringLiteral("验证码为空"));
        response.write(ret.toString().toLocal8Bit());
        return;
    }

    //
//    if(!session.contains("vercode"))
//    {
//        ret.failedMsg(QStringLiteral("未找到验证码"));
//        response.write(ret.toString().toLocal8Bit());
//        return;
//    }

    //跨域情况下，以网页请求时附带UUID，作为验证码标志
    QString sessionCode = CacheApi::instance()->get(codeid + "_vercode");
    if(sessionCode.isNull())
    {
        ret.failedMsg(QStringLiteral("未找到验证码或验证码已过期"));
        response.write(ret.toString().toLocal8Bit());
        return;
    }


    //QString sessionCode = session.get("vercode").toString();
    if(sessionCode.toLower() != vercode.toLower())
    {
        ret.failedMsg(QStringLiteral("验证码不匹配"));
        response.write(ret.toString().toLocal8Bit());
        return;
    }

    //................检查密码
    SysUser loginUser;
    if(!DbMgr::instance()->getHelper()->selectUserByName(loginUser, username))
    {
        ret.failedMsg(QStringLiteral("未找到用户或密码不正确！"));
        response.write(ret.toString().toLocal8Bit());
        return;
    }

    SysLog log("system", SysLog::LOGIN, QStringLiteral("用户登录"),
                username,
               QString(__FILE__),
               QString(__FUNCTION__),
                GlobalFunc::JsonToString(request.getParameterJson()),
                request.getPeerAddress().toString(),
                request.getHeader("User-Agent"),
                QStringLiteral("用户成功登录"));

    QString pwdAndSalt = password + loginUser.getSalt();
    QString md5Pwd = QString(QCryptographicHash::hash(pwdAndSalt.toLocal8Bit(), QCryptographicHash::Md5).toHex());
    if(md5Pwd != loginUser.getPassword())
    {
        ret.failedMsg(QStringLiteral("密码不正确！"));
        response.write(ret.toString().toLocal8Bit());

        log.setMemo(QStringLiteral("密码不正确！"));
        DbMgr::instance()->getHelper()->insertEntity(&log);
        return;
    }

    //JWT获取,并存入缓存
    QString accessToken = JwtUtil::sign(username, password);
    CacheApi::instance()->insert(username + "_token", accessToken, JwtUtil::EXPIRED_TIME);

    //session保存账户名和登录时间
    session.set("username", username);
    session.set("logintime", QTime::currentTime());

    //返回token
    ret.setData("access_token", accessToken);
    ResponseUtil::replyJson(response, ret);

    DbMgr::instance()->getHelper()->insertEntity(&log);
}

// /logout?access_token=?
void LoginController::logout(HttpRequest& request, HttpResponse& response)
{
    QString access_token = request.getParameter("access_token");
    QString username = JwtUtil::getUsername(access_token);
    CacheApi::instance()->remove(username + "_token");

    QJsonObject objParam = request.getParameterJson();
    objParam.insert("access_token", "?");
    ResponseUtil::replyJson(response, ResultJson(0, true, QStringLiteral("操作成功")));
    SysLog log("system", SysLog::LOGOUT, QStringLiteral("用户退出"),
                username,
                QString(__FILE__),
                QString(__FUNCTION__),
                GlobalFunc::JsonToString(objParam),
                request.getPeerAddress().toString(),
                request.getHeader("User-Agent"),
                QStringLiteral("用户退出成功"));
    DbMgr::instance()->getHelper()->insertEntity(&log);
}
